package sql.query;

import com.google.common.collect.Lists;
import sql.ast.Context;
import sql.ast.Node;
import sql.ast.State;
import sql.parser.SyntaxNode;

import java.util.List;
import java.util.Map;

public class ObjectDelete {
    private final ObjectVisitor objectVisitor;
    private SyntaxNode deleteSqlNode;

    public ObjectDelete(ObjectVisitor objectVisitor, SyntaxNode deleteSqlNode) {
        this.objectVisitor = objectVisitor;
        this.deleteSqlNode = deleteSqlNode;
    }

    public void delete() {
        SyntaxNode fromNode = this.deleteSqlNode.getFromNode();
        String table = fromNode.getTokenAsString();
        SyntaxNode whereNode = this.deleteSqlNode.getWhereNode();
        List list = objectVisitor.readTable(table);
        Transformer transformer = new Transformer(this.objectVisitor);
        Node conditionNode = transformer.transformConditionNode(whereNode, table);

        List deleted = Lists.newArrayList();

        int affected = 0;
        for (int i = 0; i < list.size(); i++) {
            Map map = (Map) list.get(i);
            Context context = new Context();
            context.setRow(map);
            State state = conditionNode.execute(context);
            if(state != State.True) {
                continue;
            }
            deleted.add(map);
            affected++;
        }
        list.removeAll(deleted);
        objectVisitor.writeTable(table, list);
        System.out.println(affected + "行受影响");
    }
}
